<template>
  <div class="operation-monitor">
    <div class="left-sidebar">
      <div class="real-Metrics-box">
        <titleComp titleName="实时指标概览"></titleComp>
        <div class="real-box">
          <div
            v-for="item in state.metricsList"
            :key="item"
            class="metrics-item"
          >
            <div class="top-box">
              <div
                class="metrics-icon"
                :style="{ background: item.background }"
              >
                <img :src="item.icon" alt="" />
              </div>
              <div class="metrics-label">{{ item.name }}</div>
            </div>
            <div class="bottom-box">
              <span class="metrics-num">{{ item.num }}</span>
              <span class="metrics-unit">个</span>
            </div>
          </div>
        </div>
      </div>
      <div class="alarm-type-box">
        <titleComp titleName="图片存储数量趋势"></titleComp>
        <div class="alarm-pie-chart">
          <GeneralChart :option="picStorTrendOption"></GeneralChart>
        </div>
      </div>
    </div>
    <div class="right-sidebar">
      <div class="daliy-alarm-box">
        <titleComp titleName="今日图片处理趋势"></titleComp>
        <div class="daliy-alarm-line-chart">
          <GeneralChart :option="daliyPicResolveTrendOption"></GeneralChart>
        </div>
      </div>
      <div class="last-week-alarm-box">
        <titleComp titleName="近七日图片处理趋势"></titleComp>
        <div class="lastweek-alarm-line-chart">
          <GeneralChart :option="lastWeekPicStorTrendOption"></GeneralChart>
        </div>
      </div>
      <div class="alarm-list-box">
        <titleComp titleName="当前处理图片"> </titleComp>
        <div class="current-pic-box">
          <img
            :src="state.currentHandleImgs[state.currentHandleImgIndex] || noImg"
            alt=""
            @error="setDefaultImage($event)"
          />
        </div>
      </div>
    </div>
    <div class="data-update-box">
      <span>数据更新时间:</span>
      <span>{{ state.dataUpdateTime }}</span>
    </div>
    <div class="map-container" id="modelMonitorMap"></div>
  </div>
</template>

<script setup>
import {
  getCurrentInstance,
  onBeforeUnmount,
  onMounted,
  reactive,
  ref,
  nextTick,
} from "vue";
import MapInit from "@/utils/mineMap/MapInit";
import LineBase from "@/components/chart/chartOptions/line/base.js";
import titleComp from "../situationMonitoring/title.vue";
import GeneralChart from "@/components/chart/generalChart.vue";
import access from "@/assets/img/liveData/access.png";
import avergeSecond from "@/assets/img/liveData/avergeSecond.png";
import currentPic from "@/assets/img/liveData/currentPic.png";
import currentResolve from "@/assets/img/liveData/currentResolve.png";
import historyAnalysis from "@/assets/img/liveData/historyAnalysis.png";
import video from "@/assets/img/liveData/video.png";
import accessedImg from "@/assets/img/liveData/mapPin.png";
import processingImg from "@/assets/img/liveData/mapPinGreen.png";
import otherImg from "@/assets/img/liveData/mapPinGray.png";
import noImg from "@/assets/img/page/noImg.png";
const { proxy } = getCurrentInstance();
let timer = null;
let imgTimer = null;
let switchImgTimer = null;
const state = reactive({
  currentHandleImgIndex: 0,
  currentHandleImgs: [],
  congruentPoint: [], // 聚合点数据
  metricsList: [
    {
      id: 1,
      name: "视频总路数",
      num: 0,
      icon: video,
      background: "#2275F0",
    },
    {
      id: 2,
      name: "接入路数",
      num: 0,
      icon: access,
      background: "#2CAAB8",
    },
    {
      id: 3,
      name: "当前处理路数",
      num: 0,
      icon: currentResolve,
      background: "#34AD54",
    },
    {
      id: 4,
      name: "今日分析图片数",
      num: 0,
      icon: currentPic,
      background: "#BC6106",
    },
    {
      id: 5,
      name: "历史分析图片数",
      num: 0,
      icon: historyAnalysis,
      background: "#C6A200",
    },
    {
      id: 6,
      name: "今日平均每秒处理图片数",
      num: 0,
      icon: avergeSecond,
      background: "#6456E2",
    },
  ],
  deviceMapInfo: {
    type: "FeatureCollection",
    features: [],
  },
});
const mapObject = {
  darkMapObj: null,
};
const picStorTrendOption = ref();
const daliyPicResolveTrendOption = ref();
const lastWeekPicStorTrendOption = ref();
const mapImgsList = [
  { src: processingImg, id: "processingImg" },
  { src: accessedImg, id: "accessedImg" },
  { src: otherImg, id: "otherImg" },
];

/* ==========方法======== */
const setDefaultImage = (e) => {
  debugger
  e.target.src = noImg;
}
const getUpdateTime = () => {
  let today = new Date();
  state.dataUpdateTime = today.toLocaleString();
};
const initMap = () => {
  mapObject.darkMapObj = new MapInit("modelMonitorMap", {
    center: [114.88923193324109, 40.76546125305629],
  });
  mapObject.darkMapObj.loadMapImgs(mapImgsList);
  mapObject.darkMapObj.on("load", drawDeviceMaker);
};
const drawDeviceMaker = () => {
  if (mapObject.darkMapObj) {
    addDeviceMarkerLayerSrc();
    addDeviceMarkerLayer();
  }
};
const addDeviceMarkerLayerSrc = () => {
  let source = mapObject.darkMapObj.getSource("deviceMarkerSrc");
  if (source) {
    source.setData(state.deviceMapInfo);
  } else {
    mapObject.darkMapObj.addSource("deviceMarkerSrc", {
      type: "geojson",
      data: state.deviceMapInfo,
    });
  }
};
const addDeviceMarkerLayer = () => {
  mapObject.darkMapObj.addLayer({
    id: "deviceMarkerLayer",
    type: "symbol",
    source: "deviceMarkerSrc",
    layout: {
      "icon-image": ["get", "icon"],
      "icon-size": 0.5,
      "icon-allow-overlap": true,
    },
  });
};
const getRealtimeIndicators = async () => {
  try {
    const res = await proxy.$http.getFun("pictrue/realtime/indicators");
    state.metricsList.forEach((item) => {
      switch (item.id) {
        case 1:
          item.num = res.videoTotalCount;
          break;
        case 2:
          item.num = res.videoAccessCount;
          break;
        case 3:
          item.num = res.videoCurrentCount;
          break;
        case 4:
          item.num = res.imageCountToday;
          break;
        case 5:
          item.num = res.imageCountHistory;
          break;
        case 6:
          item.num = res.imageCountPerSecond;
          break;
        default:
          break;
      }
    });
  } catch (error) {
    console.log(error);
  }
};
const getImgStorageTrend = async () => {
  try {
    const res = await proxy.$http.getFun("pictrue/storageTrend");
    picStorTrendOption.value = new LineBase({
      yAxisName: "数据量",
      dataZoomShow: false,
      lineColor: "#4B98FA",
      showTooltipName: true,
      tooltipName: "数据量",
      xaxis: res.xaxis,
      data: res.data,
    });
  } catch (error) {
    console.log(error);
  }
};
const getTodayHandleTrend = async () => {
  try {
    const res = await proxy.$http.getFun("pictrue/todayHandleTrend");
    daliyPicResolveTrendOption.value = new LineBase({
      yAxisName: "数据量",
      dataZoomShow: false,
      lineColor: "#68FFFB",
      xaxis: res.xaxis,
      data: res.data,
    });
  } catch (error) {
    console.log(error);
  }
};
const getRecentHandleTrend = async () => {
  try {
    const res = await proxy.$http.getFun("pictrue/recentHandleTrend");
    lastWeekPicStorTrendOption.value = new LineBase({
      yAxisName: "数据量",
      dataZoomShow: false,
      lineColor: "#FFD44E",
      xaxis: res.xaxis,
      data: res.data,
    });
  } catch (error) {
    console.log(error);
  }
};
const getCurrentHandleImg = async () => {
  try {
    const res = await proxy.$http.getFun("pictrue/currentHandle");
    state.currentHandleImgs = res;
    if (state.currentHandleImgs.length) {
      switchImgTimer && clearInterval(switchImgTimer);
      switchImgTimer = setInterval(swichImg, 1000);
      swichImg();
    }
  } catch (error) {
    console.log(error);
  }
};
const swichImg = () => {
  state.currentHandleImgIndex =
    (state.currentHandleImgIndex + 1) % state.currentHandleImgs.length;
};
const getDeviceMapInfo = async () => {
  try {
    const res = await proxy.$http.getFun("device/map/color");
    state.deviceMapInfo.features = handleDeviceMapInfo(res);
    nextTick(() => {
      if (!mapObject.darkMapObj) {
        initMap();
      } else {
        drawDeviceMaker();
      }
    });
  } catch (error) {
    console.log(error);
  }
};
const handleDeviceMapInfo = (resData) => {
  const features = [];
  resData?.processing?.forEach((item) => {
    const feature = {
      type: "Feature",
      geometry: {
        type: "Point",
        coordinates: [+item.longitude, +item.latitude],
      },
      properties: {
        ...item,
        icon: "processingImg",
      },
    };
    features.push(feature);
  });
  resData?.accessed?.forEach((item) => {
    const feature = {
      type: "Feature",
      geometry: {
        type: "Point",
        coordinates: [+item.longitude, +item.latitude],
      },
      properties: {
        ...item,
        icon: "accessedImg",
      },
    };
    features.push(feature);
  });
  resData?.other?.forEach((item) => {
    const feature = {
      type: "Feature",
      geometry: {
        type: "Point",
        coordinates: [+item.longitude, +item.latitude],
      },
      properties: {
        ...item,
        icon: "otherImg",
      },
    };
    features.push(feature);
  });
  return features;
};

const startTimer = () => {
  timer = setInterval(() => {
    getRealtimeIndicators();
    getImgStorageTrend();
    getTodayHandleTrend();
    getRecentHandleTrend();
    getDeviceMapInfo();
    getUpdateTime();
  }, 1000 * 60 * 5);
  imgTimer = setInterval(() => {
    getCurrentHandleImg();
  }, 1000 * 60);
};
onBeforeUnmount(() => {
  timer && clearInterval(timer);
  imgTimer && clearInterval(imgTimer);
  switchImgTimer && clearInterval(switchImgTimer);
});
onMounted(() => {
  getRealtimeIndicators();
  getImgStorageTrend();
  getTodayHandleTrend();
  getRecentHandleTrend();
  getCurrentHandleImg();
  getDeviceMapInfo();
  getUpdateTime();
  startTimer();
});
</script>
<style scoped lang="scss">
.operation-monitor {
  #modelMonitorMap {
    background-color: #0f1c38;
    height: 100%;
    width: 100%;
    z-index: 1;
  }
  overflow: visible !important;
  .left-sidebar {
    width: pxTvw(480);
    backdrop-filter: blur(6px);
    height: calc(100vh - #{pxTvh(56)});
    padding: 0 pxTvw(16);
    position: absolute;
    left: 0;
    z-index: 2;
    background-color: rgba(26, 35, 61, 0.8);
    & > .real-Metrics-box {
      margin-top: pxTvh(16);
      & > .real-box {
        margin: pxTvh(48) pxTvw(24) pxTvh(16) pxTvw(24);
        @include elasticFN(space-around, center);
        flex-wrap: wrap;
        & > .metrics-item {
          width: pxTvw(200);
          height: pxTvh(154);
          margin-bottom: pxTvh(32);
          // background: #e04f3f;
          & > .top-box {
            @include elasticFN(space-around, center);
            width: 100%;
            height: pxTvh(45);
            & > .metrics-icon {
              width: pxTvw(40);
              height: 100%;
              @include elasticFN(center, center);
              & > img {
                width: pxTvw(19);
                height: pxTvw(17);
              }
            }
            & > .metrics-label {
              font-family: PingFang SC, PingFang SC, sans-serif;
              font-weight: 400;
              @include computed_font(14);
              color: #e8f3ff;
              @include elasticFN(center, center);
              background: rgba(95, 146, 247, 0.5);
              width: calc(100% - #{pxTvw(40)});
              // padding-left: pxTvw(16);
              height: 100%;
            }
          }
          & > .bottom-box {
            height: calc(100% - #{pxTvh(45)});
            width: 100%;
            background: rgba(46, 70, 122, 0.8);
            @include elasticFN(center, center);
            & > .metrics-num {
              font-family: DIN Alternate, DIN Alternate, sans-serif;
              font-weight: bold;
              @include computed_font(40);
              color: #ffffff;
            }
            & > .metrics-unit {
              font-family: PingFang SC, PingFang SC, sans-serif;
              font-weight: 400;
              margin-top: pxTvh(18);
              @include computed_font(12);
              color: #b1b6c2;
              margin-left: pxTvw(8);
            }
          }
        }
      }
    }
    & > .alarm-type-box {
      & > .alarm-pie-chart {
        height: pxTvh(300);
        margin: pxTvh(24) auto;
      }
    }
  }
  .right-sidebar {
    width: pxTvw(480);
    padding: 0 pxTvw(16);
    backdrop-filter: blur(6px);
    height: calc(100vh - #{pxTvh(56)});
    position: absolute;
    right: 0;
    z-index: 2;
    background-color: rgba(26, 35, 61, 0.8);
    & > .daliy-alarm-box {
      margin-top: pxTvh(16);
      & > .daliy-alarm-line-chart {
        height: pxTvh(266);
        margin-top: pxTvh(16);
      }
    }
    & > .last-week-alarm-box {
      margin-top: pxTvh(28);
      & > .lastweek-alarm-line-chart {
        height: pxTvh(266);
        margin-top: pxTvh(16);
      }
    }
    & > .alarm-list-box {
      margin-top: pxTvh(24);
      & > .current-pic-box {
        margin-top: pxTvh(16);
        height: pxTvh(268);
        & > img {
          width: 100%;
          height: 100%;
        }
      }
    }
  }
  & .data-update-box {
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    @include computed_font(14);
    color: #7692ca;
    position: absolute;
    width: fit-content;
    top: pxTvh(-38);
    right: pxTvw(156);
    z-index: 2;
    & > span:nth-child(2) {
      margin-left: pxTvw(10);
    }
  }
}
</style>
